import { createRouter, createWebHistory } from 'vue-router';
import { getToken } from '@/utils/auth';
import { menu } from './modules/menu';
import { loginRouter } from './modules/login';
import useNaive from '@/hooks/useNaive';
const { loadingBar } = useNaive();
const router = createRouter({
    history: createWebHistory(), //history 模式
    routes: [
        {
            path: '/',
            name: 'container',
            // redirect: menu[0].path,
            redirect: '/login',
            component: () => import('../views/Container/index.vue'),
            children: menu
        },
        ...loginRouter,
        {
            path: '/:pathMatch(.*)',
            name: 'error-404',
            meta: {
                title: '404',
                noToken: true
            },
            component: () => import('@/views/NotFound/index.vue')
        }
    ]
});

const ignoreRul = loginRouter.map(item => item.path);
//跳转前
router.beforeEach((to, from, next) => {
    loadingBar.start();
    const token = getToken();
    const f1 = ignoreRul.includes(to.path);
    const f2 = token && token !== 'null';
    document.title = to.meta?.title;
    if (f1 || (!f1 && f2)) {
        next();
    } else {
        next({ name: 'login' });
    }
});

// 跳转后
router.afterEach(to => {
    document.title = to.meta.title;
    loadingBar.finish();
    window.scrollTo(0, 0);
});

export default router;
